import json

from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import render

# Create your views here.


# 添加购物车
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU

"""
前端： 点击加入购物车   前段发出axios请求   把 sku_id  数量 传给后端
后端
    请求  接受参数 校验
    逻辑  查看sku_id是否存在  
        保存到数据库
    返回响应
    路由  post     /carts/
"""
import base64
import pickle


class CartsView(View):
    def post(self, request):
        # - 1 接收数据
        json_date = json.loads(request.body)
        sku_id = json_date.get("sku_id")  # 商品id
        count = json_date.get("count")  # 数量
        # - 2验证数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "商品不存在"})

        try:
            count = int(count)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "数量错误"})

        # - 3 判断用户是否登录  没有登录 就是AnonymouseUser对象
        user = request.user
        if user.is_authenticated:
            # - 4 如果用户登录 保存到redis
            # - 4.1 连接redis
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # - 4.2 操作hash
            pl.hincrby("cart_%s" % user.id, sku_id, count)

            # - 4.3 操作set
            pl.sadd("selected_%s" % user.id, sku_id)
            pl.execute()
            # - 4.4返回响应
            return JsonResponse({"code": 0, "errmsg": "ok"})
        else:

            # - 5 如果用户未登录 保存到cookie
            # 获取cookie数据
            cart_cookie = request.COOKIES.get("cart")
            # 保存  字典-bytes-base64-字符串  获取 字符串-base64decode- loads- 字典
            if cart_cookie:
                carts = pickle.loads(base64.b64decode(cart_cookie))
            else:
                carts = {}
            # - 5.1 生成字典数据
            if sku_id in carts:
                # 购物车 已经有sku_id对应的商品了  做数量的累加
                count_ori = carts[sku_id]["count"]  # 取出原来的数量
                count += count_ori  # count累加count_ori后就是总的数量

            # 把数据添加到字典
            carts[sku_id] = {
                "count": count,
                "selected": True
            }

            # - 5.2字典转bytes
            carts_bytes = pickle.dumps(carts)
            # - 5.3 bytes转base64  转完后b64carts也是bytes类型
            b64carts = base64.b64encode(carts_bytes)
            # - 5.4添加cookie
            response = JsonResponse({"code": 0, "errmsg": "ok"})
            # b64carts.decode()把二进制转为字符串 保存
            response.set_cookie("cart", b64carts.decode(), max_age=3600 * 24 * 10)
            # - 6返回响应
            return response

    def get(self, request):
        # - 1判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # - 2登录用户去redis查询
            # - 2.1连接reidis
            redis_conn = get_redis_connection('carts')
            # - 2.2hash
            skuid_count = redis_conn.hgetall("cart_%s" % user.id)
            # - 2.3set
            selected_skuids = redis_conn.smembers("selected_%s" % user.id)
            # print("skuid_count", skuid_count)  # {b'15': b'13', b'4': b'1'}
            # print("selected_skuids", selected_skuids)  # {b'15', b'4'}
            carts = {}
            for sku_id, count in skuid_count.items():
                carts[int(sku_id)] = {
                    "count": int(count),
                    "selected": sku_id in selected_skuids
                }

        else:
            # - 3未登录用户去cookie查询
            # - 3.1读取cookie数据
            cart_cookie = request.COOKIES.get("cart")
            # 保存  字典-bytes-base64-字符串  获取 字符串-base64decode- loads- 字典
            if cart_cookie:  # {skId:{count:1,selected:true},skuid2:{}}
                carts = pickle.loads(base64.b64decode(cart_cookie))
            else:
                carts = {}

        # - 4根据商品id查商品信息
        # print(carts)
        # 遍历所有的商品id
        sku_ids = carts.keys()
        # 查询除所有的商品
        skus = SKU.objects.filter(id__in=sku_ids)

        # - 5把数据转为字典
        sku_list = []
        for sku in skus:
            sku_list.append({
                "id": sku.id,
                "name": sku.name,
                "price": sku.price,
                "default_image_url": sku.default_image.url,
                "count": carts[sku.id]["count"],
                "selected": carts[sku.id]["selected"],
            })

        # - 6返回响应
        return JsonResponse({"code": 0, "errmsg": "ok", "cart_skus": sku_list})

    def put(self, request):
        """修改购物车数据"""
        # 1获取用户user
        user = request.user
        # 2接受数据  修改后的 sku_id  sku_count selected
        json_data = json.loads(request.body)
        sku_id = json_data.get("sku_id")
        count = json_data.get("count")
        selected = json_data.get("selected")
        # 3验证数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseBadRequest('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return HttpResponseBadRequest('参数count有误')
        if user.is_authenticated:
            # 4 登录后 修改redis
            # 链接reids
            redis_conn = get_redis_connection('carts')
            # - hash
            redis_conn.hset("cart_%s" % user.id, sku_id, count)
            # set 无序无重复的集合
            if selected:
                redis_conn.sadd("selected_%s" % user.id, sku_id)
            else:
                redis_conn.srem("selected_%s" % user.id, sku_id)

            cart_sku = {"count": count, "selected": selected, "sku_id": sku_id}

            # 返回响应
            return JsonResponse({"code": 0, "errmsg": "ok", "cart_sku": cart_sku})
        else:
            # 4未登录
            # 修改cookie
            # 获取cookie数据
            cart_cookie = request.COOKIES.get("cart")
            # 数据解码
            carts = pickle.loads(base64.b64decode(cart_cookie))
            # 更新数据
            carts[sku_id]["count"] = count
            carts[sku_id]["selected"] = selected
            # 编码
            # - 5.2字典转bytes
            carts_bytes = pickle.dumps(carts)
            # - 5.3 bytes转base64  转完后b64carts也是bytes类型
            b64carts = base64.b64encode(carts_bytes)
            # 返回响应
            cart_sku = {"count": count, "selected": selected, "sku_id": sku_id}
            # - 5.4添加cookie
            response = JsonResponse({"code": 0, "errmsg": "ok", "cart_sku": cart_sku})
            # b64carts.decode()把二进制转为字符串 保存
            response.set_cookie("cart", b64carts.decode(), max_age=3600 * 24 * 10)
            # - 6返回响应
            return response

    def delete(self, request):
        # 1获取用户user
        user = request.user
        # 2接受数据  修改后的 sku_id  sku_count selected
        json_data = json.loads(request.body)
        sku_id = json_data.get("sku_id")
        # 3验证数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseBadRequest('商品sku_id不存在')

        if user.is_authenticated:
            # 4登录后redis里删除链接reids
            redis_conn = get_redis_connection('carts')
            # - hash
            redis_conn.hdel("cart_%s" % user.id, sku_id)
            # set
            redis_conn.srem("selected_%s" % user.id, sku_id)

            # 返回响应
            return JsonResponse({"code": 0, "errmsg": "ok"})
        else:
            # 5
            # 未登录
            # cookie里删除
            cart_cookie = request.COOKIES.get("cart")
            # 数据解码
            carts = pickle.loads(base64.b64decode(cart_cookie))
            # 更新数据
            del carts[sku_id]
            # 字典转bytes
            carts_bytes = pickle.dumps(carts)
            # bytes转base64  转完后b64carts也是bytes类型
            b64carts = base64.b64encode(carts_bytes)
            response = JsonResponse({"code": 0, "errmsg": "ok"})
            # b64carts.decode()把二进制转为字符串 保存
            response.set_cookie("cart", b64carts.decode(), max_age=3600 * 24 * 10)
            # 返回响应
            return response


class CartsSelectAllView(View):
    """全选购物车"""

    def put(self, request):
        # 接收和校验参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseBadRequest('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:
            # 用户已登录，操作redis购物车
            redis_conn = get_redis_connection('carts')
            cart = redis_conn.hgetall('cart_%s' % user.id)
            sku_id_list = cart.keys()
            if selected:
                # 全选
                redis_conn.sadd('selected_%s' % user.id, *sku_id_list)
            else:
                # 取消全选
                redis_conn.srem('selected_%s' % user.id, *sku_id_list)
            return JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})
        else:

            # 用户已登录，操作cookie购物车
            cart = request.COOKIES.get('cart')
            response = JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
                for sku_id in cart:
                    cart[sku_id]['selected'] = selected
                cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
                response.set_cookie('cart', cookie_cart, max_age=7 * 24 * 3600)

            return response


